import Router from 'koa-router';
import Redis from 'koa-redis';
import nodeMailer from 'nodemailer';
import User from './../models/users';
import Config from './../config';
import passport from './utils/passport';
import axios from './utils/axios';

let router = new Router({
  prefix: '/users'
})

let store = new Redis().client;

router.post('/signup', async (ctx) => {
  // 获取请求参数
  const {username, password, email, code} = ctx.request.body;
  // 判断验证码
  if(code) {
    // 获取验证码
    const saveCode = await store.hget(`nodemail:${username}`, 'code');
    // 获取过期时间
    const saveExpire = await store.ghet(`nodemail:${username}`, 'expire');
    if (code === saveCode) {
      if (new Date().getTime() - saveExpire > 0) {
        ctx.body = {
          code: -1,
          msg: '验证码已过期'
        }
        return false;
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '验证码错误'
      }
    }
  } else {
    ctx.body = {
      code: -1,
      msg: '请输入验证码'
    }
  }
  // 判断用户名是否存在
  let inputUser = User.find({username: username});
  if (inputUser.length) {
    ctx.body = {
      code: -1,
      msg: '用户名已存在'
    }
    return false;
  }
  // 将用户名密码写入数据库
  let writeUser = await User.create({
    username: username,
    password: password,
    email: email
  });
  if (writeUser) {
    let res = axios.post('/users/signin', {username, password});
    if (res.data && res.data.code === 0) {
      ctx.body = {
        code: 0,
        msg: '注册成功',
        user: res.data.user
      }
    }
  } else {
    ctx.body = {
      code: -1,
      msg: '注册失败'
    }
  }
})
